package com.maweirdos.springSecurity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.maweirdos.springSecurity.domain.LoginUser;
import com.maweirdos.springSecurity.domain.User;
import com.maweirdos.springSecurity.mapper.MenuMapper;
import com.maweirdos.springSecurity.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * Author:  Maweirdos
 * Date:  2024/6/19 下午9:23
 * Description:  用户信息详情实现类
 */
@Service
public class MyUserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MenuMapper menuMapper;

    /**
     * 根据用户名查询用户信息
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,username);
        User user = userMapper.selectOne(queryWrapper);
        //如果用户传进来的用户名，但是数据库没有这个用户名，就会导致我们是查不到的情况，那么就进行下面的判断。避免程序安全问题
        if(Objects.isNull(user)){
            throw new RuntimeException("用户名或者密码错误");
        }
        //手动设置权限信息
        //List<String> list = new ArrayList<>(Arrays.asList("test","adminAuth"));

        //查询数据库中权限数据
        List<String> list = menuMapper.selectPermsByUserId(user.getId());

        //把查询到的user结果，封装成UserDetails类型，然后返回。
        //但是由于UserDetails是个接口，需要实现
        return new LoginUser(user,list);
    }
}
